package com.tanhua.dubbo.server.service;

import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 使用redis的自增长类型,实现自增长的id
 */
@Service
public class IdService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 生成自增长id
     *
     * @return
     */
    public Long[] createId(String type, String objectId) {
        Long[] longs=new Long[2];
        type= StringUtils.upperCase(type);
        String hashKey = "TANHUA_HASH_ID_" + type;
        //如果ObjectId已经存在,就返回
        if(redisTemplate.opsForHash().hasKey(hashKey,objectId)){
            longs[0]=Long.valueOf(redisTemplate.opsForHash().get(hashKey,objectId).toString());
            longs[1]=1l;
            return longs;
        }

        String key = "TANHUA_ID_" + type;
        Long id = redisTemplate.opsForValue().increment(key);
        //将生成的id写入到hash表中
        redisTemplate.opsForHash().put(hashKey,objectId,id.toString());
        longs[0]=id;
        longs[1]=0l;
        return longs;
    }
}
